﻿#ifndef THREAD_POOL_HPP
#define THREAD_POOL_HPP

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
#include <type_traits> // 添加此头文件

class ThreadPool {
public:
    ThreadPool(int threads);
    ~ThreadPool();

    // 修改返回类型声明
    template<typename F, typename... Args>
    auto enques(F&& f, Args&&... args)
        -> std::future<typename std::invoke_result_t<F, Args...>>;

private:
    void worker();
    bool isstop;
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> myque;
    std::mutex mtx;
    std::condition_variable cv;
};

inline ThreadPool::ThreadPool(int threads)
    : isstop(false)
{
    for (size_t i = 0; i < threads; ++i)
        workers.emplace_back([this]() {
        this->worker();
            });
}

// 修改实现部分
template<typename F, typename... Args>
auto ThreadPool::enques(F&& f, Args&&... args)
-> std::future<typename std::invoke_result_t<F, Args...>>
{
    using return_type = std::invoke_result_t<F, Args...>;

    auto task = std::make_shared< std::packaged_task<return_type()> >(
        std::bind(std::forward<F>(f), std::forward<Args>(args)...)
    );

    std::future<return_type> res = task->get_future();

    {
        std::unique_lock<std::mutex> lockguard(this->mtx);

        if (isstop)
            throw std::runtime_error("enqueue on stopped ThreadPool");

        myque.emplace([task]() {
            (*task)();
            });
    }

    cv.notify_one();
    return res;
}

inline ThreadPool::~ThreadPool()
{
    {
        std::unique_lock<std::mutex> lock(mtx);
        isstop = true;
    }

    cv.notify_all();

    for (std::thread& worker : workers)
        worker.join();
}

void ThreadPool::worker() {
    while (true) {
        std::function<void()> task;
        {
            std::unique_lock<std::mutex> lock(mtx);
            cv.wait(lock, [this] { return this->isstop || !this->myque.empty();  });
            if (isstop && myque.empty()) return;
            task = std::move(this->myque.front());
            this->myque.pop();
        }
        task();
    }
}

#endif // THREAD_POOL_HPP